var layer;
layui.use(['layer'], function () {
    layer = layui.layer;
});

/**
 * 添加用户
 */
function addUser() {
    // 获取表单参数
    var userName = $("#userName").val(); // 用户名
    var password = $("#password").val(); // 用户密码
    var password2 = $("#password2").val(); // 用户密码
    var realName = $("#realName").val(); // 真实姓名
    var phone = $("#phone").val(); // 联系方式
    var role = $("#role").val(); // 用户角色
    var remark = $("#remark").val(); // 备注

    var param = {
        userName: userName,
        password: password,
        password2: password2,
        realName: realName,
        phone: phone,
        role: role,
        remark: remark
    }
    if (verify(param)) {
        $.ajax({
            type: "POST",
            url: "/user/addUser",
            contentType: "application/json",
            sync: true,
            data: JSON.stringify(param),
            dataType: "json",
            success: function (result) {
                console.log(result)
                if (result.code == 200) {
                    // 弹出提示
                    layer.msg('添加成功！', {anim: 3, icon: 6, time: 2000, shade: 0.1});
                    setTimeout(function () {
                        var url = '/viewUserInfo';
                        window.location.href = url;
                    }, 1000);
                } else {
                    layer.msg(result.msg, {icon: 2, offset: '100px', time: 2000});
                }
            }
        });
    }
}

function verify(param) {
    var userName = param.userName;
    var password = param.password;
    var password2 = param.password2;
    var realName = param.realName;
    var phone = param.phone;
    var role = param.role;

    if ($.isEmptyObject(userName)) {
        layer.msg('请填写用户名！', {icon: 2, offset: '100px', time: 2000});
        return false;
    } else if ($.isEmptyObject(password)) {
        layer.msg('请填用户密码！', {icon: 2, offset: '100px', time: 2000});
        return false;
    } else if ($.isEmptyObject(password2)) {
        layer.msg('请再次填写用户密码！', {icon: 2, offset: '100px', time: 2000});
        return false;
    } else if (password !== password2) {
        layer.msg('两次输入密码不相同', {icon: 2, offset: '100px', time: 2000});
        $('#password2').val('');
        return false;
    } else if ($.isEmptyObject(realName)) {
        layer.msg('请填写用户真实姓名！', {icon: 2, offset: '100px', time: 2000});
        return false;
    } else if ($.isEmptyObject(phone)) {
        layer.msg('请填写联系方式！', {icon: 2, offset: '100px', time: 2000});
        return false;
    } else if ($.isEmptyObject(role)) {
        layer.msg('请选择用户角色！', {icon: 2, offset: '100px', time: 2000});
        return false;
    }
    return true;
}

